package com.wql.test.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

/**
 * <strong>
 * Desc: pre过滤器,可以在请求被路由之前调用
 * </strong>
 * <p>Author: WeiQiLong<p>
 * Create Time:2019/8/18 10:59<p>
 */
@Component
public class PreRequestFilter extends ZuulFilter {
    /**
     * Desc:
     * pre：可以在请求被路由之前调用
     * route：在路由请求时候被调用
     * post：在route和error过滤器之后被调用
     * error：处理请求时发生错误时被调用
     * <p>
     * Author: WeiQiLong
     * Create Time:2019/8/18 11:00
     *
     * @param
     * @return java.lang.String
     */
    @Override
    public String filterType() {
        return "pre";
    }

    /**
     * Desc: 返回一个int值来指定过滤器的执行顺序，不同的过滤器允许返回相同的数字
     * Author: WeiQiLong
     * Create Time:2019/8/18 11:00
     *
     * @param
     * @return int
     */
    @Override
    public int filterOrder() {
        return 1;
    }

    /**
     * Desc: 返回一个boolean值来判断该过滤器是否要执行，true表示执行，false表示不执行。
     * Author: WeiQiLong
     * Create Time:2019/8/18 11:01
     *
     * @param
     * @return boolean
     */
    @Override
    public boolean shouldFilter() {
        return true;
    }

    /**
     * Desc: 过滤器的具体逻辑。
     * Author: WeiQiLong
     * Create Time:2019/8/18 11:01
     *
     * @param
     * @return java.lang.Object
     */
    @Override
    public Object run() throws ZuulException {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String url = request.getRequestURL().toString();
        System.out.println("pre过滤器,请求的url：" + url);
        String name = request.getParameter("name");

        context.setSendZuulResponse(true);//路由器继续放下执行
        context.setResponseStatusCode(200);
        context.set("isOk", true);

        if ("403".equalsIgnoreCase(name)) {
            context.setSendZuulResponse(false);//路由器不往下执行(不执行访问的url)
            context.setResponseStatusCode(403);
            context.setResponseBody("name的值是403");
            context.set("isOk", false);
        }

        return null;
    }
}
